package club.yuit.desktop.ui.topics.cut;

import club.yuit.desktop.layout.WrapLayout;
import club.yuit.desktop.ui.KeyValuePropertyPanel;
import club.yuit.desktop.ui.UIConstants;
import club.yuit.rmq.model.BrokerDetails;
import club.yuit.rmq.model.CUTConfig;
import club.yuit.rmq.service.RMQClusterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.TopicFilterType;
import org.apache.rocketmq.common.attribute.TopicMessageType;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: yuit
 * @date: 2023/12/12 23:38
 */
@Slf4j
class CreateOrUpdateTopicFormPanel extends JPanel {

    private JComboBox<String> clusterComboBox;


    private JTextField topic;

    private JSpinner writeQueueNums;
    private JSpinner readQueueNums;
    private JComboBox<Integer> perm;

    private JPanel propertiesPanel;

    private JComboBox<TopicMessageType> topicType;
    private JComboBox<TopicFilterType> topicFilterType;
    private JTable brokersTable;

    private RMQClusterService service;

    private Map<String, List<BrokerDetails>> brokers;

    private   CUTopicBrokerTableModel tableModel;


    public CreateOrUpdateTopicFormPanel(RMQClusterService service) {
        this.service = service;
        initUIData();
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        add(clusterBox());
        add(brokersBox());
        add(otherBox());
        add(createPropertiesPanel());
    }

    private Box clusterBox() {
        Box box = Box.createHorizontalBox();
        Box clusterBox = Box.createVerticalBox();
        clusterBox.add(createLabelPanel("集群:"));
        clusterComboBox = new JComboBox<>();
        clusterComboBox.addItem(UIConstants.ALL_CLUSTER_STR);
        for (String cluster : brokers.keySet()) {
            clusterComboBox.addItem(cluster);
        }

        clusterComboBox.addActionListener(e -> {
            String cluster = (String) clusterComboBox.getSelectedItem();
            if (cluster.equals(UIConstants.ALL_CLUSTER_STR)){
                cluster = null;
            }
            // 过滤数据
            tableModel.filterData(cluster);
            // 清除选择并刷新UI
            tableModel.clearSelected();

        });

        clusterBox.add(clusterComboBox);
        box.add(clusterBox);
        box.setMaximumSize(new Dimension(Integer.MAX_VALUE, box.getPreferredSize().height));
        return box;
    }

    /**
     * 初始化面板时网络获取broker和集群 数据
     */
    private void initUIData(){
        try {
           brokers = this.service.brokerList();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Box brokersBox() {
        Box box = Box.createVerticalBox();
        box.add(createLabelPanel("Brokers:"));

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        brokersTable = new JTable();
        tableModel = new CUTopicBrokerTableModel(brokers, brokersTable);
        JTableHeader header = brokersTable.getTableHeader();
        brokersTable.setModel(tableModel);
        header.setDefaultRenderer(new CUTTableHeaderCellRenderer(brokersTable));
        header.setReorderingAllowed(false);
        brokersTable.getColumnModel().getColumn(0).setMaxWidth(50);
        JScrollPane scrollPane = new JScrollPane(brokersTable);
        scrollPane.setMaximumSize(new Dimension(scrollPane.getPreferredSize().width,100));
        panel.add(scrollPane, BorderLayout.CENTER);
        box.add(panel);
        box.setPreferredSize(new Dimension(box.getPreferredSize().width, 100));
        return box;
    }


    private Box otherBox() {
        Box box = Box.createVerticalBox();

        // 主题名和权限组
        Box topicAndPermBox = Box.createHorizontalBox();

        // 主题
        Box topicBox = Box.createVerticalBox();
        topicBox.add(createLabelPanel("主题名:"));
        topic = new JTextField();
        topicBox.add(topic);
        topicAndPermBox.add(topicBox);
        topicAndPermBox.add(Box.createHorizontalStrut(10));

        // 权限
        Box permBox = Box.createVerticalBox();
        perm = new JComboBox<>();
        perm.addItem(0);
        perm.addItem(1);
        perm.addItem(2);
        perm.addItem(3);
        permBox.add(createLabelPanel("权限:"));
        permBox.add(perm);
        topicAndPermBox.add(permBox);

        box.add(topicAndPermBox);

        // 读写队列数box组
        Box readWriteBox = Box.createHorizontalBox();
        Box readBox = Box.createVerticalBox();
        readBox.add(createLabelPanel("读队列数:"));
        readQueueNums = numberSpinner(0, Integer.MAX_VALUE, 1);
        readBox.add(readQueueNums);

        writeQueueNums = numberSpinner(0, Integer.MAX_VALUE, 1);
        Box writeBox = Box.createVerticalBox();
        writeBox.add(createLabelPanel("写队列数:"));
        writeBox.add(writeQueueNums);

        readWriteBox.add(readBox);
        readWriteBox.add(Box.createHorizontalStrut(10));
        readWriteBox.add(writeBox);

        box.add(readWriteBox);

        // 消息类型和tag 过滤类型组
        Box msgAndTagTypeBox = Box.createHorizontalBox();

        /*Box msgBox = Box.createVerticalBox();
        msgBox.add(createLabelPanel("消息类型:"));
        topicType = new JComboBox<>();
        for (TopicMessageType type : TopicMessageType.values()) {
            topicType.addItem(type);
        }
        topicType.setSelectedItem(TopicMessageType.NORMAL);
        msgBox.add(topicType);*/

        Box tagBox = Box.createVerticalBox();
        tagBox.add(createLabelPanel("Tag过滤类型:"));
        topicFilterType = new JComboBox<>();
        for (TopicFilterType type : TopicFilterType.values()) {
            topicFilterType.addItem(type);
        }
        tagBox.add(topicFilterType);
       // msgAndTagTypeBox.add(msgBox);
       // msgAndTagTypeBox.add(Box.createHorizontalStrut(10));
        msgAndTagTypeBox.add(tagBox);
        box.add(msgAndTagTypeBox);

        box.setMaximumSize(new Dimension(Integer.MAX_VALUE, box.getPreferredSize().height));
        return box;
    }

    private Box createPropertiesPanel() {
        this.propertiesPanel = new JPanel();
        this.propertiesPanel.setLayout(new WrapLayout(WrapLayout.LEFT));
        Box mainBox = Box.createVerticalBox();

        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        controlPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, controlPanel.getPreferredSize().height));
        controlPanel.add(new JLabel("属性:"));
        JButton add = new JButton("+");
        controlPanel.add(add);

        add.addActionListener(e -> {
            KeyValuePropertyPanel panel = new KeyValuePropertyPanel(propertiesPanel);
            panel.setBorder(new LineBorder(Color.LIGHT_GRAY, 1));
            propertiesPanel.add(panel);
            propertiesPanel.updateUI();
        });

        JScrollPane sc = new JScrollPane(propertiesPanel);
        sc.setPreferredSize(new Dimension(sc.getPreferredSize().width, 100));
        sc.setBorder(null);
        mainBox.add(controlPanel);
        mainBox.add(sc);
        return mainBox;
    }

    private JPanel createLabelPanel(String label) {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT));
        panel.add(new JLabel(label));
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getPreferredSize().height));
        return panel;
    }

    private JSpinner numberSpinner(int min, int max, int step) {
        SpinnerNumberModel model = new SpinnerNumberModel(min, min, max, step);
        JSpinner spinner = new JSpinner(model);
        spinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, spinner.getPreferredSize().height));
        return spinner;
    }


    public CUTConfig getTopicConfig() {
        CUTConfig config = new CUTConfig();

        String cluster = (String) clusterComboBox.getSelectedItem();

        if (cluster.equals(UIConstants.ALL_CLUSTER_STR)){
            cluster=null;
        }

        List<String> selectedBrokers = tableModel.getSelectedBrokers();
        String name = topic.getText();
        Integer writeQueueNumsValue = (Integer) writeQueueNums.getValue();
        Integer readQueueNumsValue = (Integer) readQueueNums.getValue();
        Integer permValue = (Integer) perm.getSelectedItem();
        Map<String, String> attrs = new HashMap<>();
        Component[] components = propertiesPanel.getComponents();
        for (Component component : components) {
            if (component instanceof KeyValuePropertyPanel kp) {
                attrs.put(kp.getKey(), kp.getValue());
            }
        }

      //  TopicMessageType topicMessageType = (TopicMessageType) topicType.getSelectedItem();
        TopicFilterType filterType = (TopicFilterType) topicFilterType.getSelectedItem();
        config.setAttributes(attrs);
        config.setPerm(permValue);
        config.setTopicName(name);
        config.setReadQueueNums(readQueueNumsValue);
        config.setWriteQueueNums(writeQueueNumsValue);
        //config.setTopicMessageType(topicMessageType);
        config.setTopicFilterType(filterType);
        config.setBrokers(selectedBrokers);
        config.setCluster(cluster);
        return config;
    }

    @Override
    public Insets getInsets() {
        return new Insets(10, 10, 10, 10);
    }

}
